<template>
	<div style="position: relative;">
    <div class="query_part">
      <div class="input_search_part">
        <el-input class="input_part" clearable @focus="Onfocus" @blur="historyShow = false" @keydown.enter="search('default')" v-model="keywords" placeholder="请输入您想搜索的内容" type="text"/>
        <div class="serach_btn" @click="search('default')">搜索</div>
      </div>
    </div>
    <div v-if="historyShow" class="query_history">
      <p>最近搜索内容</p>
      <div class="query_history-content" >
        <p class="flex align-center" v-for="item in historyList" :key="item" style="cursor: pointer;" @mousedown="historySearch(item)">
          <el-icon><Clock /></el-icon><span class="query_history-text">{{ item.word }}</span>
        </p>
      </div>
    </div>
    <ul class="query_keywords flex">
      <li class="keyword flex align-center" v-for="item in keyword_arr" :key="item.api" :class="{ active: item.api === api }" @click="select(item)">{{ item.label }}</li>
    </ul>
    <div v-if="searchResultShow" class="result_count flex align-center">
      <div class="count">查询结果共 {{ total }} 条：</div>
      <div class="precise" :class="{ btn_active: drawerShow }" @click="drawerShow = true">精准筛选</div>
    </div>
    <div class="search_result">
      <div class="result flex" v-for="item in resultList" :key="item.id">
        <div class="img">
          <PreviewImg style="width:100px;height:100px;" :onlyReady="true" :src="item[img] || 'https://aplid-51.oss-cn-hangzhou.aliyuncs.com/1712484363011_4f3c824d.png'"></PreviewImg>
        </div>
        <div>
          <h3 v-html="item.titleContent"></h3>
          <div style="position: relative;">
            <p class="result-content" v-if="item.policyContent" v-html="item.policyContent"></p>
            <p class="result-content" v-else-if="item.infoContent" v-html="item.infoContent"></p>
            <p class="result-content" v-else v-html="item.otherFiled"></p>
            <div v-if="keywordArr_item.btn" class="file_btn flex align-center" @click="openFile(item)">
              <img src="@/assets/icons/viewFile.png" alt="">
              <span>查看档案</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="searchResultShow && total" class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        v-model:current-page="page"
        :page-sizes="[5, 10, 15, 20]"
        v-model:page-size="page_size"
        :background="true"
        layout="total, prev, pager, next, sizes, jumper"
        :total="total">
      </el-pagination>
    </div> 
    <AplidDialog width="65%" v-model="dialogShow" whickComm="Archives" :model="detailData" :customeHeader="detailHeader?.customeHeader">
      <component
        class="pd10"
        :is="whickComm[activeName]"
        :nowRowData="detailData"
        :actionBtn="false"
        :searchConfig="false"
        :key="activeName"
        :isWithAuth="0"
        :api="configs[BaseConfig].api"
      ></component>
		</AplidDialog>
    <!-- 政策文件和养老咨询档案 -->
    <AplidDialog width="65%" v-model="policyShow" whickComm="Archives" :model="detailData">
      <component
        class="pd10"
        :is="whickCommDetail[activeNameDetail]"
        :nowRowData="detailData"
        :key="activeNameDetail"
        :api="configs[BaseConfig]?.api"
      ></component>
		</AplidDialog>
    <el-drawer v-model="drawerShow" title="精准筛选" :destroy-on-close="true" class="drawer" :close-on-click-modal="false" @close="drawerShow = false" show-close>
      <AplidForm v-bind="configs[BaseConfig].moreSearchConfig" v-model="querryData" :showBtn="false"></AplidForm>
      <template #footer>
				<div style="flex: auto">
					<el-button @click="onReset">重置</el-button>
					<el-button type="primary" @click="search('default')"> 查询 </el-button>
				</div>
			</template>
    </el-drawer>  
  </div>
</template>
<script setup lang="ts">
import apiMod from '@/apiMod'
import { toSearchHandle } from './components/utils/index'
import { Clock } from '@element-plus/icons-vue'
import Detail from '@/views/datacenter/business/policyData/PensionInformation/Detail/index.vue'
import DocumentsDetail from '@/views/datacenter/business/policyData/PolicyDocuments/Detail/index.vue'
import { baseConfig as serviceObjAtHomeConfig, detailConfig as serviceObjAtHomeDetail } from './components/homeOldman/config'
import { baseConfig as serviceObjOrgConfig, detailConfig as serviceObjOrgDetail } from './components/oldman/config'
import { baseConfig as serviceFacilityConfig, detailConfig as serviceFacilityDetail } from './components/serviceFacility/config'
import { baseConfig as serviceOrgConfig, detailConfig as serviceOrgDetail } from './components/serviceOrg/config'
import { baseConfig as serviceOrgHomeConfig, detailConfig as serviceOrgHomeDetail } from './components/serviceOrgHome/config'
import { baseConfig as practitionerConfig, detailConfig as practitionerDetail } from './components/practitioner/config'
import { baseConfig as ServiceProviderConfig, detailConfig as ServiceProviderDetail } from './components/ServiceProvider/config'
import { baseConfig as volunteerConfig, detailConfig as volunteerDetail } from './components/volunteer/config'
import { baseConfig as expertsConfig, detailConfig as expertsDetail } from './components/experts/config'
import { baseConfig as PolicyDocumentsConfig } from './components/PolicyDocuments/config'
import { baseConfig as PensionInformationConfig, detailConfig as PensionInformationDetail } from './components/PensionInformation/config'
import AplidDialog from '@/components/AplidDialog/index.vue'
import serviceObjHome from './components/homeOldman/Archives/index.vue'
import serviceObjOrg from './components/oldman/components/Archives/index.vue'
import serviceFacility from './components/serviceFacility/components/Archives/index.vue'
import serviceOrg from './components/serviceOrg/components/Archives/index.vue'
import serviceOrgHome from './components/serviceOrgHome/components/Archives/index.vue'
import practitioner from './components/practitioner/Archives/index.vue'
import ServiceProvider from '@/views/datacenter/comprehensiveQueries/components/NewKeywords/components/ServiceProvider/Archives/index.vue'
import volunteer from './components/volunteer/Archives/index.vue'
import experts from './components/experts/Archives/index.vue'
import PolicyDocuments from './components/PolicyDocuments/index.vue'
import PensionInformation from './components/PensionInformation/index.vue'
import { isArray } from 'lodash-es'
import { useCommonStore } from '@/stores/common'
import { getAreaObj } from '@/utils/util'
const { getDictList } = useCommonStore()
const keywords = ref('')
const api = ref('search_homeOldman')
const BaseConfig = ref('')
const page = ref(1)
const page_size = ref(10)
const total = ref(0)
const resultList = ref([])
const dialogShow = ref(false)
const detailData = ref()
const activeName = ref('serviceObjHome')
const drawerShow = ref(false)
const querryData = ref({})
const searchResultShow = ref(false)
const historyShow = ref(false)
const historyList = ref([])
const keywordArr_item = ref()
const img = ref('homeAgreement')
const detailHeader = ref()
const policyShow = ref(false)
const activeNameDetail = ref()
let newQuerry

const keyword_arr = [
  { label: '服务对象（居家）', api: 'search_homeOldman', component: 'serviceObjHome', config: 'serviceObjAtHomeConfig', img: 'image', btn: true, detail: 'serviceObjAtHomeDetail' },
  { label: '服务对象（机构）', api: 'search_serviceObject', component: 'serviceObjOrg', config: 'serviceObjOrgConfig', img: 'image', btn: true, detail: 'serviceObjOrgDetail' },
  { label: '社区居家养老服务设施', api: 'search_serviceFacility', component: 'serviceFacility', config: 'serviceFacilityConfig', img: 'doorHead', btn: true, detail: 'serviceFacilityDetail'},
  { label: '养老机构', api: 'search_serviceOrgBase', component: 'serviceOrg', config: 'serviceOrgConfig', img: 'doorHeadImgs', btn: true, detail: 'serviceOrgDetail' },
  { label: '养老服务运营单位', api: 'search_serviceOrgHome', component: 'serviceOrgHome', config: 'serviceOrgHomeConfig', img: 'orgHomeLogo', btn: true, detail: 'serviceOrgHomeDetail' },
  { label: '从业人员', api: 'search_foundationPractitioners', component: 'practitioner', config: 'practitionerConfig', img: 'staffPhoto', btn: true, detail: 'practitionerDetail' },
  { label: '养老行业服务商', api: 'search_serviceProvider', component: 'ServiceProvider', config: 'ServiceProviderConfig', img: 'providerLogo', btn: true, detail: 'ServiceProviderDetail' },
  { label: '志愿者', api: 'search_volunteer', component: 'volunteer', config: 'volunteerConfig', img: 'volunteerPhoto', btn: true, detail: 'volunteerDetail' },
  { label: '养老专家数据', api: 'search_professor', component: 'experts', config: 'expertsConfig', img: 'professorImg', btn: true, detail: 'expertsDetail' },
  { label: '政策文件', api: 'search_policyDocument', component: 'PolicyDocuments', config: 'PolicyDocumentsConfig', img: 'doorHead', btn: true, detail: '' },
  { label: '养老资讯', api: 'search_news', component: 'PensionInformation', config: 'PensionInformationConfig', img: 'infoImg', btn: true, detail: '' },
] 
const whickComm = {
  serviceObjHome,
	serviceObjOrg,
  serviceFacility,
  serviceOrg,
  serviceOrgHome,
  practitioner,
  ServiceProvider,
  volunteer,
  experts,
  PolicyDocuments,
  PensionInformation
}
const whickCommDetail = {
  Detail,
  DocumentsDetail,
}
const configs = {
  serviceObjAtHomeConfig,
  serviceObjOrgConfig,
  serviceFacilityConfig,
  serviceOrgConfig,
  serviceOrgHomeConfig,
  practitionerConfig,
  ServiceProviderConfig,
  volunteerConfig,
  expertsConfig,
  PolicyDocumentsConfig,
  PensionInformationConfig
}
const detailConfigs = {
  serviceObjAtHomeDetail,
  serviceObjOrgDetail,
  serviceFacilityDetail,
  serviceOrgDetail,
  serviceOrgHomeDetail,
  practitionerDetail,
  ServiceProviderDetail,
  volunteerDetail,
  expertsDetail,
}

const openFile = async(item) => {
  await getDictList(configs[BaseConfig.value].dictcodes)
  const area: any = getAreaObj(item, '', 'set')
	detailData.value = {
    ...item,
    areas: area.areaIds,
		areasName: area.names,
  }
  if(keywordArr_item.value.detail) {
    detailHeader.value = detailConfigs[keywordArr_item.value.detail]
    dialogShow.value = true
  }else {
    if(keywordArr_item.value.label == '养老资讯') {
      activeNameDetail.value = 'Detail'
    } else {
      activeNameDetail.value = 'DocumentsDetail'
    }
    policyShow.value = true
  }
}

const select = (item) => { 
  keywordArr_item.value = item
  api.value = item.api
  activeName.value = item.component
  BaseConfig.value = item.config
  onReset()
  search('history')
}

const Onfocus = ()=> {
  if(historyList.value.length) {
    historyShow.value = true
  } 
}

const historySearch = (item) => {
  keywords.value = item.word
  onReset()
  search('history')
  historyShow.value = false
}

const search = (type) => {
  if(!keywords.value) {
    return ElMessage({
      message: '请输入关键词',
      type: 'warning',
    }) 
  }
  let tempQuery = {
    ...querryData.value
  }
  if(tempQuery) {
    tempQuery = toSearchHandle(configs[BaseConfig.value]?.moreSearchConfig, configs[BaseConfig.value]?.reserveSearchConfig, tempQuery)
  }
  drawerShow.value = false
  // 默认搜索或历史搜索将当前页置为1
  if(type !== 'page') {
    page.value = 1
  }
  apiMod[api.value]({
      ...tempQuery,
      current: page.value,
      keyWord: keywords.value,
      size: page_size.value
    }).then(res=>{
    img.value = keywordArr_item.value.img
    if(type == 'default') { //存储搜索历史到缓存
      let historyLog = {
        word: keywords.value
      }
      if(historyList.value.length > 4) {
        historyList.value.pop()
      }
      historyList.value.unshift(historyLog)
      sessionStorage.setItem('historyList',JSON.stringify(historyList.value))
    }
    resultList.value = res.data.records.map(item=>{
      let titleContent
      if(keywordArr_item.value.config == 'serviceObjAtHomeConfig' || keywordArr_item.value.config == 'serviceObjOrgConfig') {
        titleContent = (item.name || '') + ' ' + (item.age || '') + ' ' + (item.elderlyTypeLabel || '') + ' ' + (item.crAddress || '')
      } else if (keywordArr_item.value.config == 'serviceFacilityConfig') {
        titleContent = (item.soleValue || '') + ' ' + (item.standardLabel || '') + ' ' + (item.typeLabel || '') + ' ' + (item.address || '')
      } else if (keywordArr_item.value.config == 'serviceOrgConfig') {
        titleContent = (item.organizationName || '') + ' ' + (item.organizationLevelLabel || '') + ' ' + (item.organizationTypeLabel || '') + ' ' + (item.organizationAddress || '')
      } else if (keywordArr_item.value.config == 'serviceOrgHomeConfig') {
        titleContent = (item.orgHomeName || '') + ' ' + (item.organizationLevelLabel || '') + ' ' + (item.registerTypeLabel || '') + ' ' + (item.address || '')
      } else if (keywordArr_item.value.config == 'practitionerConfig') {
        titleContent = (item.practitionersName || '') + ' ' + (item.phone || '') + ' ' + (item.unitName || '') + ' ' + (item.occupationTypeLabel || '')
      } else if (keywordArr_item.value.config == 'ServiceProviderConfig') {
        titleContent = (item.providerName || '') + ' ' + (item.registerProvinceName || '') + (item.registerCityName || '') + (item.registerAreaName || '') + (item.registerStreetName || '') + (item.registerCommunityName || '')
      } else if (keywordArr_item.value.config == 'volunteerConfig') {
        titleContent = (item.volunteerName || '') + ' ' + (item.volunteerPhone || '') + ' ' + (item.registerOrganization || '')
      } else if (keywordArr_item.value.config == 'expertsConfig') {
        titleContent = (item.professorName || '') + ' ' + (item.phone || '') + ' ' + (item.enterpriseName || '')
      } else if (keywordArr_item.value.config == 'PolicyDocumentsConfig') {
        titleContent = (item.policyTitle || '') + ' ' + (item.publishDate || '')
      } else if (keywordArr_item.value.config == 'PensionInformationConfig') {
        titleContent = (item.infoTitle || '') + ' ' + (item.publishDate || '')
      }
      // 标题高亮处理
      let keywordsArr = keywords.value.split(' ')
      titleContent = highlightKeywords(titleContent, keywordsArr)
      return {
        ...item,
        titleContent
      }
    })
    total.value = res.data.total 
    searchResultShow.value = true
  }) 
}

const onReset = () => {
	querryData.value = {}
}

//高亮标题
const highlightKeywords = (text, keywords) => {
  const highlightedText = text.replace(new RegExp(`(${keywords.join('|')})`, 'gi'), '<span style="color: red;">$1</span>');
  return highlightedText;
}

const handleSizeChange = (val: number) => {
  page_size.value = val
  search('history')
}

const handleCurrentChange = (val: number) => {
  page.value = val
  search('page')
}

onMounted(()=>{
  keywordArr_item.value = keyword_arr[0]
  BaseConfig.value = keyword_arr[0].config
  historyList.value = JSON.parse(sessionStorage.getItem('historyList')) || []
})

</script>

<style scoped lang="scss">
.query_part {
	display: flex;
	flex-direction: row;
	justify-content: flex-start;
	align-items: center;
}
.input_search_part {
	width: 1056px;
	max-width: 1056px;
	height: 48px;
	border-radius: 8px;
	background: #fff;
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	align-items: center;
	box-sizing: border-box;
	margin-right: 20px;
}
.input_part {
	height: 48px;
	font-size: 16px;
	text-align: left;
	color: #1c1c28;
	line-height: 48px;
}
.input_part:focus {
	outline: none;
}
.serach_btn {
	width: 124px;
	height: 48px;
	border-radius: 0 8px 8px 0;
	background: #0052d9;
	line-height: 48px;
	text-align: center;
	font-weight: 700;
	font-size: 20px;
	letter-spacing: 0.2px;
	color: #fff;
	cursor: pointer;
}
.query_keywords {
  margin-top: 20px;
  width: 1200px;
  row-gap: 10px;
  column-gap: 20px;
  flex-wrap: wrap;
  .keyword {
    width: 200px;
    height: 35px;
    justify-content: center;
    cursor: pointer;
    background-color: #fff;
    border-radius: 5px;
    &:hover {
      border: 1px solid #0052d9;
    }
  }
  .active {
    background-color: #0052d9;
    color: #fff;
    &:hover {
      color: #000;
      transform: scale(1.01);
    }
  }
}
.result_count {
  margin: 20px 0;
  .count {
    font-size: 20px;
    font-weight: 800;
  }
  .precise {
    padding: 5px 10px;
    border: 1px solid #d9d9d9;
    border-radius: 5px;
    column-gap: #d9d9d9;
    cursor: pointer;
    &:hover {
      border: 1px solid #0052d9;
    }
  }
  .btn_active {
    background-color: #0052d9;
    color: #fff;
  }
}
.search_result {
  display: flex;
  flex-direction: column;
  gap: 35px;
  .result {
    height: 80px;
    gap: 20px;
    h3 {
      width: 1200px;
      text-overflow:ellipsis;
      white-space:nowrap;
      overflow:hidden;
    }
    .img {
      width: 100px;
      height: 100px;
      border-radius: 2px;
    }
    &-content {
      margin-top: 15px;
      line-height: 25px;
      height: 50px;
      width: 1100px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
    }
    .file_btn {
      gap: 5px;
      img {
        width: 15px;
        height: 17px;
      }
      position: absolute;
      right: 0px;
      bottom: 0;
      margin-left: 10px;
      color: #0052d9;
      cursor: pointer;
    }
  }
}
.pagination {
  margin-top: 40px;
}
.query_history {
  position: absolute;
  z-index: 999;
  top: 48px;
  left: 0;
  padding: 10px;
  background-color: #fff;
  height: 230px;
	width: calc(100% - 600px);
  border-radius: 5px;
  border: 1px solid #0052d9;
  border-top: none;
  &-content {
    padding: 15px;
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  &-text {
    margin-left: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
:deep(.drawer) {
  padding: 20px;
}
</style>
